package com.mmall.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class TokenCache {

    private static Logger logger= LoggerFactory.getLogger(TokenCache.class);
    public static final String TOKEN_PRIFIX="token_";

    private static LoadingCache<String,String> loadingCache= CacheBuilder.newBuilder()
            .initialCapacity(1000).maximumSize(10000)
            .expireAfterAccess(12, TimeUnit.HOURS)
            .build(new CacheLoader<String, String>() {

                //默认的数据加载实现,当调用get的时候获取不到对应key的value,就调用此方法
                @Override
                public String load(String s) throws Exception {

                    //避免字符串比较的时候报空指针异常
                    return "null";
                }
            });


    public static void setKey(String key,String value){

        loadingCache.put(key,value);
    }

    public static String getValue(String key){

        String value=null;
        try {
             value=loadingCache.get(key);
            if ("null".equals(value)){

                return null;
            }
            return value;
        } catch (ExecutionException e) {
            logger.error("loadCache get error ",e);
        }

        return null;
    }
}
